package com.liwentao.seckill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liwentao.seckill.entity.Order;
import com.liwentao.seckill.entity.SeckillOrder;
import com.liwentao.seckill.entity.User;
import com.liwentao.seckill.entity.vo.GoodsVo;
import com.liwentao.seckill.mapper.GoodsMapper;
import com.liwentao.seckill.mapper.OrderMapper;
import com.liwentao.seckill.result.R;
import com.liwentao.seckill.result.ResponseEnum;
import com.liwentao.seckill.service.IGoodsService;
import com.liwentao.seckill.service.IOrderService;
import com.liwentao.seckill.service.ISeckillOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;

@RestController
@RequestMapping("/seckill/seckill")
@Api(value = "秒杀",tags = "秒杀控制器")
public class SeckillController {
    @Resource
    private IGoodsService goodsService;
    @Resource
    private ISeckillOrderService seckillOrderService;
    @Resource
    private IOrderService orderService;

    @PostMapping("/doSeckill")
    @ApiOperation(value = "doSeckill",notes = "秒杀")
    public R doSeckill(User user, @ApiParam(name = "goodsId",value = "商品id",required = true) Long goodsId, Model model){
        System.out.println(goodsId);
        //检验是否登录
        if(null==user){
            return R.error(ResponseEnum.UNLOG_ERROR);
        }
        model.addAttribute("user", user);
        R goodsVoByGoodsId = goodsService.findGoodsVoByGoodsId(goodsId);
        GoodsVo goods=(GoodsVo) goodsVoByGoodsId.getData().get("goodsVo");
        //查询货物库存
        if(goods.getStockCount()<1){
            return R.error(ResponseEnum.GOODSNULL_ERROR);
        }
        SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>()
                .eq("user_id", user.getId())
                .eq("goods_id", goodsId));
        //检测订单是否重复，单人买一个
        if(seckillOrder!=null){
            return R.error(ResponseEnum.ORDEREXIST_ERROR);
        }
        //执行秒杀
        Order order=orderService.seckill(user,goods);
        model.addAttribute("order", order);
        model.addAttribute("goods", goods);
        return R.ok().data("order", order).data("goods", goods);
    }

}
